<?php
/************************
 *  Codenova.pl Project
 *  Created by: Kamil Mrzygłód
 *
 *  (c) 2013 by Codenova.pl
 *  All Right Reserved
 ***********************/

namespace Gotcha\App\Extensions;

// Gotcha error class

use Gotcha\App\GotchaBootstrap;
use Gotcha\App\Types\String;

final class GotchaErrorsExtension extends GotchaBootstrap {
    public static function throwError(String $msg, String $param1 = null, String $param2 = null, String $param3 = null) {
        if (!parent::$error_handler_is_set) {
            set_error_handler(array('GotchaErrorsExtension', 'gotchaErrorHandler'));
            parent::$error_handler_is_set = true;
        }

        // If there is not optional parameters, just trigger error
        if (!$param1 && !$param2 && !$param3) {
            trigger_error($msg, E_USER_ERROR);
        } else {
            // If we have optional parameters, we expect find
            // format signs, which will be overwritten
            $formatted_msg = sprintf($msg, $param1, $param2, $param3);
            trigger_error($formatted_msg, E_USER_ERROR);
        }
    }

    public function gotchaErrorHandler($errno, $errstr, $errfile, $errline) {
        if (!(error_reporting() && $errno)) {
            // This error code is not included in error_reporting
            return false;
        }

        switch ($errno) {
            case E_USER_ERROR:
                echo '<pre><strong>Błąd:</strong> '.$errstr.'<br><strong>Plik:</strong> '.$errfile.'<br><strong>Linia:</strong> '.$errline.'</pre></pre>';
                break;

            case E_USER_WARNING:
                break;

            case E_USER_NOTICE:
                break;

            case E_RECOVERABLE_ERROR:
                echo '<pre><strong>Błąd:</strong> '.$errstr.'<br><strong>Plik:</strong> '.$errfile.'<br><strong>Linia:</strong> '.$errline.'</pre></pre>';
                GotchaLogsExtension::createNewLogEntry(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_VARIABLE_TYPING'))));
                exit;

            default:
                echo '<pre><strong>Błąd:</strong> '.$errstr.'<br><strong>Plik:</strong> '.$errfile.'<br><strong>Linia:</strong> '.$errline.'</pre></pre>';
                break;
        }

        // Don't execute PHP internal error handler
        return true;
    }
}